package BaseService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"time"
)

func Add(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	data := r.GetMap()
	// 增加附加数据，本步骤可以插入默认数据
	if req.AddInsertData != nil {
		otherData := req.AddInsertData(r)
		for k, v := range otherData {
			data[k] = v
		}
	}
	// 添加前方法
	if req.AddBeforeFn != nil {
		respRes := req.AddBeforeFn(r, data)
		if respRes.Code != 0 {
			return respRes
		}
	}
	// 去除 基础列
	delBaseIgnoreProperty(data)
	data["create_at"] = time.Now().Unix()

	// 过滤不正确的参数
	data, err := toolsDb.FilterColumnParams(g.DB(), false, data, req.TableName)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	res, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, req.TableName).Insert(data)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	id, err := res.LastInsertId()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	// 尝试删除缓存
	if g.Cfg().GetBool("site.BaseCacheIsOpen") {
		tools.ClaerCacheByKeyPrefix("backCache:" + req.TableName + ":*")
	}
	return response.SuccessByRequestMessageData(nil, "添加成功", g.Map{
		"id": id,
	})
}
